package log

import (
	"runtime"

	"github.com/sirupsen/logrus"
)

const (
	maximumCallerDepth int = 5
	skipFrames         int = 10
)

// hook logrus 没有skipCaller 🐶
func NewReportCallerHook() logrus.Hook {
	hook := reportCallerHook{}
	return &hook
}

type reportCallerHook struct{}

func (hook *reportCallerHook) Fire(entry *logrus.Entry) error {
	entry.Caller = getCaller()
	return nil
}

func (hook *reportCallerHook) Levels() []logrus.Level {
	return logrus.AllLevels
}

// getCaller retrieves the name of the first non-logrus calling function
func getCaller() *runtime.Frame {
	// Restrict the lookback frames to avoid runaway lookups
	pcs := make([]uintptr, maximumCallerDepth)
	depth := runtime.Callers(skipFrames, pcs)
	frames := runtime.CallersFrames(pcs[:depth])

	f, _ := frames.Next()

	return &f
}
